package bll

import (
	"context"

	"proto/dto"
	log "signal/collector/logger"
	"signal/lib/trace_log"
	"signal/model"
	"signal/utils"
)

var Upgrade = &upgrade{}

// 服务端向设备发起升级
type upgrade struct{}

func (u *upgrade) init() func() {
	return func() {}
}

func (u *upgrade) OTA(ctx context.Context, in *dto.UpgradeRequest) error {
	var (
		err  error
		sn   = in.Sn
		id   uint8
		addr = []byte(in.Addr)
	)
	// add end of string
	addr = append(addr, 0)

	defer func() {
		trace_log.DebugLogger(in.Sn, "OTA 执行 data:", utils.ToJsonString(in), " err:", err)
	}()

	if id, err = Session.GetRequestID(sn); err != nil {
		log.Error("get request error ", err)
		return err
	}
	packet := model.BuildPacket(model.CmdUpgrade, id, addr)

	if err = Session.Send(sn, packet.ToHexBytes()); err != nil {
		log.Error("send OTA command error: ", err)
		return err
	}
	log.Info("send OTA command success")
	return nil
}
